#ifndef MYUDPRECEIVE_H
#define MYUDPRECEIVE_H

//视频数据来源
#include <QObject>
#include <QUdpSocket>
#include <QThread>
#include <QNetworkInterface>
#include <QElapsedTimer>
#include <qnetworkinterface.h>
#include <QNetworkDatagram>

#include "head.h"
#include "SafeQueue.h"

// 定义UDP数据结构
struct UdpData {
    QString ip;
    quint16 port;
    QByteArray data;
};

class MyUdpWork;

class MyUdpReceive : public QObject
{
    Q_OBJECT
public:
    explicit MyUdpReceive(const VIDEO_SAVE_CONFIG&  config, QObject *parent = nullptr);
    ~MyUdpReceive();

    void static sendStatus(bool status, QString bindIP, quint16 bindPort, QString dstIP, quint16 dstPort);   //对于cameralink中的灰度图而言，需要发送指令控制发送开关

signals:
    void sigToSaveData(const QString ip, const quint16 port, const QByteArray arr);      //发送数据至存储

    void  sigStopProcessing();

private:
    QThread *m_thread;  //线程类
    MyUdpWork *m_work;  //udp工作类

};

class MyUdpWork : public QObject
{
    Q_OBJECT
public:
    explicit MyUdpWork(QString ip, QString netName, quint16 port, QObject *parent = nullptr);

    void initSinglecast();  //初始化单播
    void initMulticast(); //初始化组播
    void initBroadcast();   //初始化广播
    int getNetCardIndex(QString interfaceName); //获取网卡名对应的index

private:
    QUdpSocket *m_udpReceive;
    QString m_ip;
    quint16 m_port;
    QString m_netName;

    SafeQueue<UdpData> m_dataQueue;  // 使用带最大容量的队列
    QThread *m_processThread;
    bool m_isProcessing;
    quint64 m_droppedCount;  // 记录丢弃的数据数量

    // 帧率统计变量
    QElapsedTimer m_fpsTimer;
    int m_frameCount = 0;
    double m_currentFps = 0.0;

    int m_netCardIndex = -1;

public slots:
    void onReceive();

    void startProcessing();

    void stopProcessing();

    void processData();  // 处理队列中的数据


signals:
    void sigToSaveData(const QString ip, const quint16 port, const QByteArray arr);      //发送数据至存储

    void sigDataDropped(quint64 totalDropped);  // 通知数据被丢弃

    void sigFrameRate(double fps);  // 新增：帧率信号
};

#endif // MYUDPRECEIVE_H
